# Copyright (c) 2022, hzmes and contributors
# For license information, please see license.txt

import frappe
from frappe.model.document import Document
from frappe.model.mapper import get_mapped_doc


class SRMSupplyPlan(Document):
	# 从之前的after_insert改为distribute,由JS在前端调用
	@frappe.whitelist()
	def distribute(self):
		# 分供应商拆分
		supplier = []
		for s in self.orderitem:
			if s.assign_qty > 0:
				supplier.append(s.supplier_number)
		for supplier_number in set(supplier):
			self.make_supplyplan_of_supplier(self.name, supplier_number)


	# 生成供应商回复表，每个供应商一张单以隔离权限
	def make_supplyplan_of_supplier(self, source_name, supplier_number, target_doc=None):
		# 获取供应商的默认联系人
		receive_person = frappe.db.get_list('SRM User Default', filters={'setting_value': supplier_number}, fields=['user'])
		doc = get_mapped_doc(
			"SRM Supply Plan",
			source_name,
			{
				"SRM Supply Plan": {
					"doctype": "SRM Supply Plan Of Supplier",
					"field_map": {
							"name": "from_supply_plan", 
							# "receive_person": receive_person[0].user,
							# "supplier_number": supplier_number,
						},
					# "validation": {
					# 	"docstatus": ["=", 1],
					# },
				},
				"SRM Supply Plan OrderItem": {
					"doctype": "SRM Supply Plan Of Supplier OrderItem",
					"field_map": {
						"name": "from_supply_plan_orderitem",
					},
					# "postprocess": update_item,
					"condition": lambda doc: doc.supplier_number == supplier_number,
				},
			},
			target_doc,
			ignore_permissions=True
		)
		doc.is_anwser = 0
		doc.supplier_number = supplier_number
		if receive_person:
			if receive_person[0].user:
				doc.receive_person = receive_person[0].user
		doc.insert(ignore_permissions=True)
		return doc
